import router from './router'
import store from './store'
import axios from 'axios'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getPageTitle from './utils/get-page-title'
import { getToken } from './utils/auth' // get token from cookie
import Login from './service/login'

/* 请求拦截器（请求之前的操作） */
axios.interceptors.request.use(
  // 是否需要设置 token
  (config) => {
    // const isToken = (config.headers || {}).isToken === false
    // if (getToken() && !isToken) {
    //   config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    // }

    store.dispatch('loading/setLoadingStatus', true)
    return config
  },
  err => {
    store.dispatch('loading/setLoadingStatus', false)
    return Promise.reject(err)
  })

/* 请求之后的操作 */
axios.interceptors.response.use((res) => {
  store.dispatch('loading/setLoadingStatus', false)
  return res
}, (err) => {
  store.dispatch('loading/setLoadingStatus', false)
  return Promise.reject(err)
})

NProgress.configure({ showSpinner: false })

// const whiteRoutes = ['/login', '/404']
router.beforeEach((to, from, next) => {
  NProgress.start()
  document.title = getPageTitle(to.meta.title)

  // const hasToken = getToken()
  //
  // if (hasToken) {
  //   debugger
  //   if (to.path === '/login') {
  //     debugger
  //     next()
  //     NProgress.done()
  //   } else {
  //     Login.asyncRoute()
  //       .then(data => {
  //         const transFn = path => {
  //           return () => import('@/' + path)
  //         }
  //         function toRoutes(arrs) {
  //           arrs.forEach(item => {
  //             if (item.component) {
  //               item.component = transFn(item.component)
  //             }
  //             if (item.children) {
  //               return toRoutes(item.children)
  //             }
  //           })
  //           return arrs
  //         }
  //
  //         const routes = toRoutes(data.data)
  //         store.commit('user/SET_ASYNC_ROUTES', routes)
  //         router.addRoutes(routes)
  //       })
  //       .catch(error => console.log(error))
  //   }
  // } else {
  //   if (whiteRoutes.includes(to.path)) {
  //     debugger
  //     next()
  //   } else {
  //     debugger
  //     next('/login')
  //   }
  // }

  /* Login.asyncRoute()
    .then(data => {
      const transFn = path => {
        return () => import('@/' + path)
      }
      function toRoutes(arrs) {
        arrs.forEach(item => {
          if (item.component) {
            item.component = transFn(item.component)
          }
          if (item.children) {
            return toRoutes(item.children)
          }
        })
        return arrs
      }

      const routes = toRoutes(data.data)
      store.commit('user/SET_ASYNC_ROUTES', routes)
      router.addRoutes(routes)
    })
    .catch(error => console.log(error))*/

  next()
  NProgress.done()
})

router.afterEach(() => {
  NProgress.done()
})
